<template>
  <div class="page-container">
    <page-form :model="form" ref="formRef" :rules="rules" layout="vertical">
      <page-form-row>
        <!-- 借调类型：跨门店调车0 借调(借入)1 借调(借出) 2 -->
        <page-form-item field="type" label="借调类型" :rules="{ required: true, message: '请选择借调类型' }">
          <a-select
            placeholder="请选择"
            v-model="form.type"
            @change="changeTypeFn"
            :disabled="query.source == 'order' || (formList.includes(query.form) && query.source == 2)"
          >
            <a-option v-for="item in dict.typeEnum" :key="item.value" :label="item.label" :value="item.value" />
          </a-select>
        </page-form-item>
      </page-form-row>
      <!-- 不选借调类型，不展示 -->
      <template v-if="form.type !== undefined">
        <page-form-row>
          <page-form-item label="关联启程订单号">
            <i-input
              v-model="form.refCode"
              :maxLength="20"
              :disabled="query.source == 'order' || form.type == 2 ? true : false"
              @keyup="form.refCode = form.refCode.replace(/[\W]/g, '')"
              @blur="handleCodeBlur"
            />
          </page-form-item>
          <page-form-item
            field="siteId"
            label="调入后车辆归属门店"
            :rules="{ required: true, message: '请选择调入后车辆归属门店' }"
            required
          >
            <remote-select
              placeholder="请选择调入后车辆归属门店"
              :disabled="query.source == 'order' ? true : isOrderFlag ? true : false"
              v-model="form.siteId"
              :params="{ oldId: form.siteId, siteStatusList: [10] }"
              type="site_listBystaff"
              @change="siteChange"
              @initList="initSiteListCb"
              v-if="resetSiteSelect"
            />
            <a-select v-else />
          </page-form-item>

          <page-form-item label="归属车场">
            <a-input v-model="form.siteCarPark" disabled :placeholder="form.siteId ? '未配置' : '选择调入后车辆归属门店后带入'" />
          </page-form-item>

          <page-form-item field="sourceId" label="被调车的门店或同行" :rules="sourceIdRule" required style="position: relative">
            <div style="position: absolute; top: 0px; left: 145px">
              <a-tooltip>
                <template #content>
                  <div style="font-size: 14px">
                    <div>借调类型为跨门店调车时，可选的借调公司为门店数据</div>
                    <div>借调类型为借入或借出时，可选的借调公司为同行数据</div>
                  </div>
                </template>
                <icon-question-circle />
              </a-tooltip>
            </div>
            <!-- 跨门店调车取本商户门店，借入借出选同行 -->
            <remote-select
              v-if="form.type == 0"
              placeholder="请选择被调车的门店或同行"
              v-model="form.sourceId"
              :params="{ oldId: form.sourceId, siteStatusList: [10] }"
              type="site_listBystaff"
              @change="storeChange"
            />
            <!-- 同行 -->
            <remote-select
              ref="companySelectRef"
              v-else
              placeholder="请选择被调车的门店或同行"
              v-model="form.sourceId"
              :params="{ industryStatus: 20, tradeNew }"
              type="sameIndustry_list"
              @change="companyChange"
            />
            <div class="link-text" type="text" v-if="form.type != 0" @click="handleAddTrade">
              <icon-plus style="font-size: 12px; font-weight: 800" /> <a-link style="color: #1890ff">新增同行</a-link></div
            >
          </page-form-item>

          <!-- 车辆选择 begin -->
          <page-form-item
            label="车牌号"
            field="licenseNo"
            v-if="form.type == 1"
            :rules="{ required: true, message: '请输入车牌号' }"
            required
          >
            <i-input v-model="form.licenseNo" :maxLength="10" :disabled="formList.includes(query.form) && query.source == 2" />
          </page-form-item>
          <page-form-item field="carId" label="车牌号" :rules="{ required: true, message: '请选择车牌号' }" v-else required>
            <remote-select
              placeholder="请选择车牌号"
              v-model="form.carId"
              :params="{ siteId: form.type == 2 ? form.siteId : form.sourceId }"
              type="car_transfer_car_by_site"
              :mustParentShow="form.type == 2 ? !form.siteId : !form.sourceId"
              :mustParentTip="form.type == 2 ? '请选择归属门店' : '请选择被调车的门店或同行'"
              @change="carChange"
            />
          </page-form-item>
          <!-- 车辆选择 end -->

          <!-- 车型选择 begin -->
          <page-form-item label="车型" v-if="form.type == 0">
            <i-input v-model="form.modelName" disabled placeholder="选择车辆后带出" />
          </page-form-item>
          <page-form-item field="modelId" label="车型" v-else :rules="{ required: form.type == 1 ? true : false, message: '请选择车型' }">
            <remote-select
              v-model="form.modelId"
              :allow-clear="false"
              type="car_model_tenantList"
              :disabled="formList.includes(query.form) && query.source == 2"
            />
          </page-form-item>
          <!-- 车型选择 end -->

          <page-form-item
            label="调车时间"
            field="startTime"
            required
            :rules="{ required: true, message: '请选择调车时间' }"
            v-if="form.type == 0"
          >
            <i-date-picker class="w-full" v-model="form.startTime" show-time value-format="YYYY-MM-DD HH:mm:ss" />
          </page-form-item>
          <page-form-item label="借调费" v-if="form.type == 0">
            <a-input-number
              v-model="form.amount"
              placeholder="请输入"
              :min="0"
              :max="1000000000"
              :precision="2"
              @blur="setContractAmount"
            />
          </page-form-item>
          <page-form-item
            label="调车周期"
            field="shuntRangeTime"
            v-if="form.type != 0"
            style="position: relative"
            :rules="[
              { required: true, message: '请选择调车周期' },
              { type: 'array', minLength: form.shuntRangeTime.length == 0 ? 0 : 2, message: '请完善调车周期' },
            ]"
          >
            <i-range-picker
              v-model="form.shuntRangeTime"
              show-time
              value-format="YYYY-MM-DD HH:mm:ss"
              @popup-visible-change="changeshuntRangeTime"
              @clear="handleClear"
              popup-container=".page-container"
              style="width: 100%"
            />
            <a style="position: absolute; top: 0; right: 0; color: #1890ff" type="primary" v-if="form.type != 0"
              >租期：{{ form.rentDays || '-' }}</a
            >
          </page-form-item>

          <page-form-item label="收款账号">
            <i-input v-model="form.contractCarPurchaseEditVo.receiveAccount" :maxLength="20" />
          </page-form-item>
          <page-form-block v-if="form.type == 0">
            <a-col>
              <div class="page-title">合同信息</div>
            </a-col>
            <page-form-item
              label="合同编号"
              field="contractCarPurchaseEditVo.contractNo"
              :rules="{ match: /^[a-zA-Z0-9]{0,30}$/, message: '支持填写数字及字母，最多30位' }"
            >
              <i-input :max-length="30" v-model="form.contractCarPurchaseEditVo.contractNo" />
            </page-form-item>
            <page-form-item label="上传合同">
              <upload-attach class="upload-contract" v-model="form.contractCarPurchaseEditVo.contractFileId" :maxMB="20" />
            </page-form-item>
          </page-form-block>
        </page-form-row>

        <page-form-block v-if="form.type != 0">
          <a-col>
            <div class="page-title">结算信息</div>
          </a-col>
          <page-form-item label="是否分期" size="1">
            <a-radio-group v-model="form.contractCarPurchaseEditVo.useInstallment" :options="plainOptions" />
          </page-form-item>
          <!-- 分期 -->
          <template v-if="form.contractCarPurchaseEditVo.useInstallment == 1">
            <page-form-item label="首付">
              <i-input-number v-model="form.contractCarPurchaseEditVo.initialAmount"> </i-input-number>
            </page-form-item>
            <page-form-item label="尾款">
              <i-input-number v-model="form.contractCarPurchaseEditVo.balanceAmount"> </i-input-number>
            </page-form-item>
            <page-form-item
              field="contractCarPurchaseEditVo.lnstalmentNum"
              label="期数"
              required
              :rules="[{ required: true, message: '请输入期数', trigger: 'blur' }]"
            >
              <i-input-number
                :precision="0"
                :min="1"
                :max="100"
                v-model="form.contractCarPurchaseEditVo.lnstalmentNum"
                unit="期"
                @blur="onBlur"
              />
            </page-form-item>
            <page-form-item
              field="contractCarPurchaseEditVo.amountPerPeriod"
              label="每期金额"
              required
              :rules="[{ required: true, message: '请输入每期金额', trigger: 'blur' }]"
            >
              <i-input-number v-model="form.contractCarPurchaseEditVo.amountPerPeriod"> </i-input-number>
            </page-form-item>
            <page-form-item
              field="contractCarPurchaseEditVo.lnstalmentFirstDate"
              label="第一期付款日"
              required
              :rules="[{ required: true, message: '请输入第一期付款日', trigger: 'blur' }]"
            >
              <i-date-picker class="w-full" v-model="form.contractCarPurchaseEditVo.lnstalmentFirstDate" />
            </page-form-item>
            <a-col>
              <div
                class="contract-operate-wrapper"
                :class="[!form.contractCarPurchaseEditVo.useInstallment ? 'contract-operate-wrapper2' : '']"
              >
                <div class="all-count"
                  >合计：<span class="num">{{ countTotal }}元</span></div
                >
                <div class="contract-operate-content">
                  <a-button type="primary" style="margin-left: 10px" @click="viewPaymentPlanFn">查看付款计划</a-button>
                </div>
              </div>
            </a-col>
          </template>
          <!-- 不分期 -->
          <template v-else>
            <page-form-item label="借调费">
              <a-input-number
                v-model="form.amount"
                placeholder="请输入"
                :min="0"
                :max="1000000000"
                :precision="2"
                @blur="setContractAmount"
              />
            </page-form-item>
          </template>
        </page-form-block>
        <page-form-block v-if="form.type != 0">
          <a-col>
            <div class="page-title">合同信息</div>
          </a-col>
          <page-form-item
            label="合同编号"
            field="contractCarPurchaseEditVocontractNo"
            :rules="{ match: /^[a-zA-Z0-9]{0,30}$/, message: '支持填写数字及字母，最多30位' }"
          >
            <i-input :max-length="30" v-model="form.contractCarPurchaseEditVocontractNo" />
          </page-form-item>
          <page-form-item field="contractCarPurchaseEditVo.contractSignDate" label="合同开始日期">
            <i-date-picker
              class="w-full"
              :disabled-date="(date) => disabledDateFn(date, 'start')"
              v-model="form.contractCarPurchaseEditVo.contractSignDate"
            />
          </page-form-item>
          <page-form-item field="contractCarPurchaseEditVo.contractEndDate" label="合同结束日期">
            <i-date-picker
              class="w-full"
              :disabled-date="(date) => disabledDateFn(date, 'end')"
              v-model="form.contractCarPurchaseEditVo.contractEndDate"
            />
          </page-form-item>
          <page-form-item label="上传合同">
            <upload-attach class="upload-contract" v-model="form.contractCarPurchaseEditVo.contractFileId" :maxMB="20" />
          </page-form-item>
        </page-form-block>
      </template>
    </page-form>
  </div>
  <page-form-footer @ok="submitFn" :ok-loading="okLoading" />
  <!-- 查看付款计划 -->
  <car-payment-plan-modal ref="carPaymentPlanModalRef" />
  <!-- 新增同行 -->
  <AddTrade ref="addTradeRef" @refreshData="handleAddTradeOk" />
  <!-- 排车周期校验 -->
  <PlatoonCarCheckModal ref="platoonCarCheckModalRef" />
</template>

<script setup lang="ts" name="CarTransferForm">
  import AddTrade from '../compoents/addTrade.vue'

  import { ref, provide, reactive, onMounted, computed, nextTick, watch } from 'vue'
  import { useRoute } from 'vue-router'
  import { computeLeaseTerm, saveCarTransfer, planList } from '@/api/asset/carTransfer'
  import { getList } from '@/api/order/sOrder'
  import useNavigate from '@/hooks/useNavigate'
  import { usePageDict } from '@/hooks/useDict'
  import dayjs from 'dayjs'
  import { Message } from '@arco-design/web-vue'
  import { checkLicenseNo, checkReturnCar, payablePreview } from '@/api/asset/car.js'
  import carPaymentPlanModal from '../../../car/car-manage/components/car-payment-plan-modal.vue'

  const formList = ['car-return', 'car-manage']
  const dict = usePageDict('carTransferDict')
  const { navigateBack } = useNavigate()
  const route = useRoute()
  const query = route.query

  const plainOptions = reactive([
    { label: '是', value: 1 },
    { label: '否', value: 0 },
  ])

  const form = ref<any>({
    shuntRangeTime: [],
    payMethod: '1',
    contractCarPurchaseEditVo: { useInstallment: 0 },
  })
  // 表单规则
  const rules = {}
  const sourceIdRule = computed(() => {
    // 跨门店调车时，不能与调入后车辆归属门店相同
    if (form.value.type == 0) {
      return [
        { required: true, message: '请选择被调车的门店或同行' },
        {
          validator: (value, cb) => {
            if (form.value.siteId == value) {
              cb('跨门店调车时，不能与调入后车辆归属门店相同')
              return false
            }
            return true
          },
        },
      ]
    } else {
      return { required: true, message: '请选择被调车的门店或同行' }
    }
  })

  // 关联订单号修改自动使用订单门店，并置灰门店不可修改
  const isOrderFlag = ref(false) //判断是否存在待排车短租订单
  const resetSiteSelect = ref(true)
  const handleCodeBlur = () => {
    isOrderFlag.value = false
    if (form.value.refCode) {
      getList({ orderCode: form.value.refCode, pageSize: 10, pageNumber: 1 }).then((res) => {
        if (res.code == 200) {
          const result = res.result.data || []
          if (result && result.length == 1) {
            if (result[0].orderStatus == 10) {
              isOrderFlag.value = true
              form.value.siteId = result[0].siteId || undefined
              resetSiteSelect.value = false
              nextTick(() => {
                resetSiteSelect.value = true
              })
            } else {
              Message.error('您填写订单号已排车')
              form.value.refCode = undefined
            }
          } else {
            Message.error('您填写的订单不存在')
            form.value.refCode = undefined
          }
        }
      })
    }
  }
  const countTotal = ref<any>(0)
  const initCount = (num: any) => {
    return Number(num) || 0
  }
  const renderAllCount = () => {
    countTotal.value = (
      initCount(form.value.contractCarPurchaseEditVo.initialAmount) +
      initCount(form.value.contractCarPurchaseEditVo.balanceAmount) +
      initCount(form.value.contractCarPurchaseEditVo.lnstalmentNum) * initCount(form.value.contractCarPurchaseEditVo.amountPerPeriod)
    ).toFixed(2)
  }
  watch(
    () => form.value.contractCarPurchaseEditVo,
    () => {
      renderAllCount()
    },
    { immediate: true, deep: true }
  )

  const disabledDateFn = (date, type) => {
    if (type == 'start') {
      let endDate = form.value.contractCarPurchaseEditVo.contractEndDate
      if (endDate) {
        return dayjs(date).startOf('day').valueOf() > dayjs(endDate).valueOf()
      } else {
        return false
      }
    } else {
      let startDate = form.value.contractCarPurchaseEditVo.contractSignDate
      if (startDate) {
        return dayjs(startDate).valueOf() > dayjs(date).startOf('day').valueOf()
      } else {
        return false
      }
    }
  }
  // 切换门店
  const siteChange = (value, option = {}) => {
    form.value.siteName = option.siteName
    form.value.siteCarPark = option.siteCarPark
    // 借出清空车辆
    if (form.value.type == 2) {
      form.value.carId = undefined
    }
  }
  // 选择借调公司 （门店）
  const storeChange = (value, option) => {
    form.value.sourceName = option.siteName
    if (form.value.type == 0) {
      form.value.carId = undefined
    }
  }
  // 选择借调公司（同行）change
  const companyChange = (val, option = {}) => {
    form.value.sourceName = option.industryName
  }
  // 车辆选择change
  const carChange = (value, option = {}) => {
    form.value.licenseNo = option.licenseNo
    form.value.modelId = option.modelId
    form.value.modelName = option.modelName
  }
  // 获取门店列表，默认选择第一个门店
  const firstStore = ref({})
  const initSiteListCb = (list) => {
    firstStore.value = list[0]
    form.value.siteId = firstStore.value.id
    form.value.siteName = firstStore.value.siteName
    form.value.siteCarPark = firstStore.value.siteCarPark
  }

  // 选择借调类型
  const changeTypeFn = (e) => {
    isOrderFlag.value = false
    form.value = {
      shuntRangeTime: [],
      payMethod: '1',
      contractCarPurchaseEditVo: { useInstallment: 0 },
    }
    form.value.type = e
    form.value.startTime = dayjs().format('YYYY-MM-DD HH:mm:ss')

    if (e != 0) {
      form.value.shuntRangeTime[0] = dayjs().format('YYYY-MM-DD HH:mm:ss')
    }
  }

  // 选择借调周期
  const changeshuntRangeTime = (e) => {
    console.log(form.value.shuntRangeTime)
    if (!e && form.value.shuntRangeTime.length && form.value.shuntRangeTime.length == 2) {
      form.value.startTime = form.value.shuntRangeTime[0]
      form.value.endTime = form.value.shuntRangeTime[1]
      computeLeaseTerm({
        startTime: form.value.shuntRangeTime[0],
        endTime: form.value.shuntRangeTime[1],
      }).then((res) => {
        if (res.code == 200) {
          form.value.rentDays = res.result
        }
      })
    }
  }

  // 清空借调周期
  const handleClear = () => {
    form.value.shuntRangeTime = []
    form.value.startTime = undefined
    form.value.endTime = undefined
    form.value.rentDays = undefined
  }

  // 设置总金额
  const setContractAmount = () => {
    form.value.contractCarPurchaseEditVo.contractAmount = form.value.amount
  }

  // 查看付款计划
  const carPaymentPlanModalRef = ref()
  const viewPaymentPlanFn = () => {
    let contractInfo = form.value.contractCarPurchaseEditVo || {}
    let { amountPerPeriod, lnstalmentNum, lnstalmentFirstDate, contractSignDate, contractEndDate } = contractInfo
    // 定义字段和对应的名称
    const requiredFields = [
      { value: amountPerPeriod, name: '每期金额' },
      { value: lnstalmentNum, name: '期数' },
      { value: lnstalmentFirstDate, name: '第一期付款日' },
    ]
    // 找到未填写的字段名称
    const missingFields = requiredFields.filter((field) => !field.value).map((field) => field.name)
    if (!amountPerPeriod) {
      formRef.value.setFields({
        ['contractCarPurchaseEditVo.amountPerPeriod']: {
          status: 'error',
          message: '请输入每期金额',
        },
      })
    }
    if (!lnstalmentNum) {
      formRef.value.setFields({
        ['contractCarPurchaseEditVo.lnstalmentNum']: {
          status: 'error',
          message: '请输入期数',
        },
      })
    }
    if (!lnstalmentFirstDate) {
      formRef.value.setFields({
        ['contractCarPurchaseEditVo.lnstalmentFirstDate']: {
          status: 'error',
          message: '请输入第一期付款日',
        },
      })
    }
    if (missingFields.length > 0) {
      Message.warning({
        content: `请先填写${missingFields.join('、')}字段！`,
        closable: true,
        duration: 5000,
      })
    } else {
      let param = {
        initialAmount: contractInfo.initialAmount, //首付
        balanceAmount: contractInfo.balanceAmount, //尾款
        lnstalmentNum,
        lnstalmentAmount: amountPerPeriod,
        lnstalmentFirstDate,
        contractSignDate,
        contractEndDate,
        purchaseCarDate: form.value?.shuntRangeTime[0], //调车周期开始日期
      }
      if (form.value.type == 1) {
        param.carSource = 2
        payablePreview(param).then((res) => {
          let obj = Object.assign(res.result, { source: form.value.type })
          carPaymentPlanModalRef.value.open(obj)
        })
      } else {
        planList(param).then((res) => {
          let obj = Object.assign(res.result, { source: form.value.type })
          carPaymentPlanModalRef.value.open(obj)
        })
      }
    }
  }

  provide('form', form)
  const formRef = ref()
  const platoonCarCheckModalRef = ref()
  const okLoading = ref(false)

  const confirmCarTransfer = (param, noticeSuccess) => {
    saveCarTransfer(param)
      .then(() => {
        noticeSuccess()
        navigateBack()
      })
      .finally(() => {
        okLoading.value = false
      })
  }

  const submitFn = (noticeSuccess) => {
    formRef.value.validate(async (error) => {
      if (!error) {
        if (form.value.type == 2) {
          platoonCarCheckModalRef.value.confirm({
            title: '请确认是否借出车辆？',
            submitBtnLoading: okLoading,
            params: {
              refId: form.value.id,
              startTime: form.value.startTime,
              endTime: form.value.endTime,
              useType: 12,
              carId: form.value.carId,
            },
            onOk: (successCb) => {
              const param = {
                ...form.value,
              }
              saveCarTransfer(param)
                .then(() => {
                  noticeSuccess()
                  navigateBack()
                })
                .finally(() => {
                  successCb()
                })
            },
          })
          return
        }

        const param = {
          ...form.value,
        }

        okLoading.value = true

        if (form.value.type === 1) {
          try {
            const _ = await checkLicenseNo({ licenseNo: param.licenseNo, vin: param.vin, carInfoId: param.carInfoId })

            const { code } = await checkReturnCar({ licenseNo: param.licenseNo, modelId: param.modelId })
            if (code == 200) {
              confirmCarTransfer(param, noticeSuccess)
            } else {
              okLoading.value = false
            }
          } catch (error) {
            console.log('error', error)
            okLoading.value = false
          }
        } else {
          confirmCarTransfer(param, noticeSuccess)
        }
      }
    })
  }

  // 新增同行
  const addTradeRef = ref(null)
  const handleAddTrade = () => {
    addTradeRef.value.show()
  }
  // 新增同行成功
  const tradeNew = ref(0)
  const handleAddTradeOk = (data) => {
    form.value.sourceId = data.id
    form.value.sourceName = data.industryName
    tradeNew.value++
  }

  onMounted(() => {
    if (formList.includes(query.form) && query.source) {
      if (query.source == 2) {
        form.value.type = 1
        form.value.licenseNo = query.licenseNo
        form.value.modelId = query.modelId
        form.value.vin = query.vin
        form.value.carInfoId = query.carInfoId
      }
    }

    if (query.source == 'order') {
      form.value.refCode = query.orderCode
      form.value.siteId = Number(query.siteId)
      form.value.startTime = query.startTime != 'null' ? query.startTime : undefined
      form.value.endTime = query.endTime != 'null' ? query.endTime : undefined
      form.value.shuntRangeTime = query.startTime != 'null' ? [query.startTime, query.endTime] : []
      form.value.type = 1
      // 计算周期
      changeshuntRangeTime()
    }
  })
</script>

<style lang="less" scoped>
  .empty-custom-fee {
    margin: 30px 0 35px;
    justify-content: center;
    :deep(.arco-empty) {
      .arco-empty-description {
        color: #d8d8d8;
        font-size: 12px;
      }
      .arco-icon {
        color: #d8d8d8;
      }
    }
  }
  .inspect_cost {
    background: #f7f8fa;
    box-sizing: border-box;
    padding: 20px;
  }
  .cosTotal {
    font-size: 14px;
    font-family: PingFang SC-Semibold, PingFang SC;
    font-weight: 600;
    color: #1d2129;
    line-height: 22px;
  }
  .costNum {
    font-size: 18px;
    font-family: PingFang SC-Semibold, PingFang SC;
    font-weight: 600;
    color: #165dff;
    line-height: 22px;
  }
  .link-text {
    position: absolute;
    top: 0px;
    right: 0;
    color: #1890ff;
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
  .contract-operate-wrapper {
    width: 100%;
    height: 66px;
    margin-bottom: 20px;
    background: #f2f3f5;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 20px;
    .contract-operate-content {
      .upload-contract {
        display: inline-block;
      }
      .view-payment-plan {
        margin-left: 16px;
      }
    }
  }
  .page-title {
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 16px;
    color: #1d2129;
    margin-bottom: 14px;
  }
  .all-count {
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 16px;
    color: #1d2129;
    text-align: left;
    font-style: normal;
    text-transform: none;
    .num {
      color: #1890ff;
    }
  }
</style>
